import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../theme/app_theme.dart';
import 'dart:math';
import 'dart:developer' as developer;

class PregnancyScreen extends StatefulWidget {
  const PregnancyScreen({super.key});

  @override
  State<PregnancyScreen> createState() => _PregnancyScreenState();
}

class _PregnancyScreenState extends State<PregnancyScreen> {
  
  dynamic _pregnancyInfo;
  
  List<dynamic> _recentFoodSearches = [];
  bool _isLoading = false;
  String _searchQuery = '';
  
  List<dynamic> _searchResults = [];

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  void _loadData() {
    setState(() => _isLoading = true);
    
    
    Future.microtask(() {
      try {
        
        _pregnancyInfo = {
          'lastPeriodDate': DateTime.now().subtract(const Duration(days: 180)), 
          'expectedDueDate': DateTime.now().add(const Duration(days: 104)),
          'currentWeek': 25,
          'daysInCurrentWeek': 3,
          'pregnancyProgress': 0.58
        };
        
        
        _recentFoodSearches = [
          {
            'name': '苹果',
            'safetyLevel': 'safe',
            'description': '富含维生素和纤维素，对孕妇和胎儿有益',
            'notes': '建议每天吃1-2个',
          },
          {
            'name': '咖啡',
            'safetyLevel': 'caution',
            'description': '含有咖啡因，过量可能影响胎儿发育',
            'notes': '每天不超过一杯（200ml）',
          },
        ];
      } catch (e) {
        developer.log('加载数据失败: $e');
      } finally {
        setState(() => _isLoading = false);
      }
    });
  }

  void _searchFood() {
    if (_searchQuery.isEmpty) return;
    
    setState(() => _isLoading = true);
    
    
    Future.microtask(() {
      try {
        
        _searchResults = [
          {
            'name': _searchQuery,
            'safetyLevel': Random().nextInt(2) == 0 ? 'safe' : 'caution',
            'description': '这是搜索结果的描述信息',
            'notes': '这是一些使用建议',
          },
          
        ];
      } catch (e) {
        developer.log('搜索食物失败: $e');
        _searchResults = [];
      } finally {
        setState(() => _isLoading = false);
      }
    });
  }

  void _showFoodDetail(dynamic food) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(food?.name ?? '食物'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  food?.name ?? '食物',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                  decoration: BoxDecoration(
                    color: _getSafetyLevelColor(food?.safetyLevel),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Text(
                    _getSafetyLevelText(food?.safetyLevel),
                    style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            Text('描述:', style: AppTheme.subtitleStyle),
            const SizedBox(height: 8),
            Text(food?.description ?? '暂无描述', style: AppTheme.bodyStyle),
            const SizedBox(height: 16),
            Text('注意事项:', style: AppTheme.subtitleStyle),
            const SizedBox(height: 8),
            Text(food?.notes ?? '暂无注意事项', style: AppTheme.bodyStyle),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  Color _getSafetyLevelColor(dynamic level) {
    
    if (level == null) return Colors.grey;
    
    
    String levelStr = level.toString().split('.').last.toLowerCase();
    
    switch (levelStr) {
      case 'safe':
      case '安全':
        return Colors.green;
      case 'caution':
      case '谨慎':
        return Colors.orange;
      case 'unsafe':
      case '不安全':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  String _getSafetyLevelText(dynamic level) {
    
    if (level == null) return '未知';
    
    
    String levelStr = level.toString().split('.').last.toLowerCase();
    
    switch (levelStr) {
      case 'safe':
      case '安全':
        return '安全';
      case 'caution':
      case '谨慎':
        return '谨慎';
      case 'unsafe':
      case '不安全':
        return '不安全';
      default:
        return '未知';
    }
  }

  void _showUltrasoundInterpretationDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('B超单解读'),
        content: Container(
          width: double.maxFinite,
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('常见B超指标解读:', style: AppTheme.subtitleStyle),
                const SizedBox(height: 16),
                _buildUltrasoundIndex('双顶径(BPD)', '胎儿头部两侧顶骨之间的距离，反映胎儿头部发育情况'),
                _buildUltrasoundIndex('股骨长(FL)', '胎儿大腿骨的长度，用于评估胎儿发育状况'),
                _buildUltrasoundIndex('腹围(AC)', '胎儿腹部的周长，反映胎儿腹部发育'),
                _buildUltrasoundIndex('羊水指数(AFI)', '评估羊水量的多少，正常范围8-24cm'),
                _buildUltrasoundIndex('胎盘成熟度', '分为0-3级，反映胎盘的功能状态'),
              ],
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  Widget _buildUltrasoundIndex(String name, String description) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(name, style: AppTheme.bodyStyle.copyWith(fontWeight: FontWeight.bold)),
        Text(description, style: AppTheme.bodyStyle.copyWith(fontSize: 12)),
        const SizedBox(height: 8),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.background,
      appBar: AppBar(
        backgroundColor: AppTheme.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.pop(context),
          color: AppTheme.textPrimary,
        ),
        title: Text('孕期模式', style: AppTheme.titleStyle),
      ),
      body: _isLoading ? _buildLoadingView() : _buildMainView(),
    );
  }

  Widget _buildLoadingView() {
    return const Center(child: CircularProgressIndicator());
  }

  Widget _buildMainView() {
    if (_pregnancyInfo == null) {
      return const Center(child: Text('暂无孕期信息'));
    }

    final weeks = _pregnancyInfo!.currentWeek;
    final days = _pregnancyInfo!.daysInCurrentWeek;
    final progress = _pregnancyInfo!.pregnancyProgress;

    return SingleChildScrollView(
      child: Column(
        children: [
          
          Container(
            margin: const EdgeInsets.all(16),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: AppTheme.white,
              borderRadius: BorderRadius.circular(12),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.05),
                  blurRadius: 10,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text('孕 $weeks 周 $days 天', style: AppTheme.titleStyle.copyWith(fontSize: 28)),
                const SizedBox(height: 16),
                Text('预产期: ${DateFormat('yyyy年MM月dd日').format(_pregnancyInfo!.expectedDueDate)}', style: AppTheme.bodyStyle),
                const SizedBox(height: 20),
                
                
                Column(
                  children: [
                    Text('孕期进度', style: AppTheme.subtitleStyle),
                    const SizedBox(height: 12),
                    SizedBox(
                      height: 8,
                      width: double.infinity,
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(4),
                        child: LinearProgressIndicator(
                          value: progress, 

                          backgroundColor: AppTheme.background,
                          valueColor: AlwaysStoppedAnimation<Color>(AppTheme.primaryColor),
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text('${(progress * 100).toInt()}%', style: AppTheme.bodyStyle.copyWith(fontSize: 12)),
                  ],
                ),
              ],
            ),
          ),

          
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 16),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: AppTheme.white,
              borderRadius: BorderRadius.circular(12),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.05),
                  blurRadius: 10,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('胎儿发育情况', style: AppTheme.subtitleStyle),
                const SizedBox(height: 16),
                _buildFetalDevelopmentInfo(weeks),
              ],
            ),
          ),

          
          Container(
            margin: const EdgeInsets.all(16),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: AppTheme.white,
              borderRadius: BorderRadius.circular(12),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.05),
                  blurRadius: 10,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('实用功能', style: AppTheme.subtitleStyle),
                const SizedBox(height: 16),
                GridView.count(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  crossAxisCount: 2,
                  crossAxisSpacing: 12,
                  mainAxisSpacing: 12,
                  children: [
                    _buildFunctionCard(
                      icon: Icons.search,
                      title: '食物安全性查询',
                      subtitle: '查询孕期能吃什么',
                      onTap: () => _showFoodSearchDialog(),
                    ),
                    _buildFunctionCard(
                      icon: Icons.medical_information,
                      title: 'B超单解读',
                      subtitle: '解读B超单关键数据',
                      onTap: _showUltrasoundInterpretationDialog,
                    ),
                  ],
                ),
              ],
            ),
          ),

          const SizedBox(height: 24),
        ],
      ),
    );
  }

  void _showFoodSearchDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('食物安全性查询'),
        content: Container(
          width: double.maxFinite,
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextField(
                  decoration: InputDecoration(
                    hintText: '输入食物名称搜索',
                    suffixIcon: IconButton(
                      icon: const Icon(Icons.search),
                      onPressed: _searchFood,
                    ),
                  ),
                  onChanged: (value) => _searchQuery = value,
                  onSubmitted: (value) => _searchFood(),
                ),
                const SizedBox(height: 16),
                
                
                _isLoading
                    ? const CircularProgressIndicator()
                    : _searchResults.isNotEmpty
                        ? Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text('搜索结果:', style: AppTheme.subtitleStyle),
                              const SizedBox(height: 8),
                              ..._searchResults.map((food) => _buildFoodItem(food)),
                            ],
                          )
                        : _recentFoodSearches.isNotEmpty
                            ? Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text('最近搜索:', style: AppTheme.subtitleStyle),
                                  const SizedBox(height: 8),
                                  ..._recentFoodSearches.map((food) => _buildFoodItem(food)),
                                ],
                              )
                            : Text('请输入食物名称进行搜索', style: AppTheme.bodyStyle),
              ],
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  Widget _buildFoodItem(dynamic food) {
    return GestureDetector(
      onTap: () => _showFoodDetail(food),
      child: Container(
        padding: const EdgeInsets.all(12),
        margin: const EdgeInsets.only(bottom: 8),
        decoration: BoxDecoration(
          color: AppTheme.background,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(food.name, style: AppTheme.bodyStyle),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
              decoration: BoxDecoration(
                color: _getSafetyLevelColor(food.safetyLevel).withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                _getSafetyLevelText(food.safetyLevel),
                style: TextStyle(
                  color: _getSafetyLevelColor(food.safetyLevel),
                  fontSize: 12,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildFetalDevelopmentInfo(int weeks) {
    
    Map<int, Map<String, String>> developmentInfo = {
      1: {'size': '0.2毫米', 'description': '受精卵开始分裂，形成胚泡'},
      2: {'size': '0.5毫米', 'description': '胚泡植入子宫内壁，开始形成胎盘'}, 
      3: {'size': '1-2毫米', 'description': '神经管开始形成，心脏开始发育'}, 
      4: {'size': '5毫米', 'description': '形成基本器官，手臂和腿部开始出现'}, 
      5: {'size': '8毫米', 'description': '面部特征开始形成，心脏开始跳动'}, 
      6: {'size': '1.5厘米', 'description': '手指和脚趾开始形成，眼睛和耳朵清晰可见'}, 
      7: {'size': '2.5厘米', 'description': '所有主要器官都已形成，开始有轻微活动'}, 
      8: {'size': '3.5厘米', 'description': '开始出现胎动，所有重要器官继续发育'}, 
      9: {'size': '4.5厘米', 'description': '面部特征更加清晰，手指和脚趾分开'}, 
      10: {'size': '6厘米', 'description': '胎儿可以弯曲手臂和腿部，指甲开始形成'}, 
      11: {'size': '7.5厘米', 'description': '生殖器开始发育，手指和脚趾甲形成'}, 
      12: {'size': '9厘米', 'description': '胎儿可以吞咽和踢腿，外生殖器可识别性别'}, 
      13: {'size': '11厘米', 'description': '面部特征形成，汗腺开始发育'}, 
      14: {'size': '13厘米', 'description': '毛发开始生长，面部表情开始形成'}, 
      15: {'size': '15厘米', 'description': '骨骼开始硬化，皮肤薄且透明'}, 
      16: {'size': '16.5厘米', 'description': '听力开始发育，胎儿能够听到声音'}, 
      17: {'size': '19厘米', 'description': '脂肪开始积累，皮肤开始变厚'}, 
      18: {'size': '20.5厘米', 'description': '手指和脚趾有清晰的指纹，可感知光线'}, 
      19: {'size': '22厘米', 'description': '头发和指甲继续生长，开始有睡眠周期'}, 
      20: {'size': '25.4厘米', 'description': '体重约300克，胎动更加明显'}, 
      21: {'size': '26厘米', 'description': '皮肤开始变红，胎脂形成保护皮肤'}, 
      22: {'size': '27厘米', 'description': '眼睛开始睁开，肺部开始发育'}, 
      23: {'size': '28厘米', 'description': '大脑发育迅速，胎儿开始有规律睡眠'}, 
      24: {'size': '29厘米', 'description': '体重约600克，肺部开始产生表面活性物质'}, 
      25: {'size': '30厘米', 'description': '睫毛和眉毛形成，皮肤变得更加不透明'}, 
      26: {'size': '35厘米', 'description': '体重约800克，胎儿可以睁开和闭上眼睛'}, 
      27: {'size': '36厘米', 'description': '大脑和神经系统继续成熟，胎动更加有力'}, 
      28: {'size': '37厘米', 'description': '体重约1000克，肺和其他器官接近成熟'}, 
      29: {'size': '38厘米', 'description': '脂肪继续积累，皮肤变得圆润'}, 
      30: {'size': '39厘米', 'description': '体重约1300克，头发更长更密'}, 
      31: {'size': '40厘米', 'description': '肺部和消化系统继续发育成熟'}, 
      32: {'size': '42厘米', 'description': '体重约1600克，皮肤变得更加光滑'}, 
      33: {'size': '43厘米', 'description': '神经系统发育更加完善，体温调节能力增强'}, 
      34: {'size': '45厘米', 'description': '体重约2000克，胎儿位置开始调整为头位'}, 
      35: {'size': '46厘米', 'description': '脂肪层增厚，为出生做准备'}, 
      36: {'size': '47厘米', 'description': '体重约2500克，大多数器官已发育成熟'}, 
      37: {'size': '48厘米', 'description': '足月胎儿，随时可能出生'}, 
      38: {'size': '49厘米', 'description': '体重约3000克，完全准备好出生'}, 
      39: {'size': '50厘米', 'description': '体重约3200克，脂肪层进一步增厚'}, 
      40: {'size': '51厘米', 'description': '体重约3500克，理想的出生时间'}, 
    };

    
    final info = developmentInfo[weeks] ?? developmentInfo[min(weeks, 40)]!;
    
    return Column(
      children: [
        
        Container(
          height: 150,
          decoration: BoxDecoration(
            color: AppTheme.background,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(Icons.child_care, size: 64, color: AppTheme.primaryColor),
                const SizedBox(height: 8),
                Text('胎儿大小：${info['size']}', style: AppTheme.bodyStyle),
              ],
            ),
          ),
        ),
        const SizedBox(height: 16),
        
        
        Text('发育情况：', style: AppTheme.subtitleStyle),
        const SizedBox(height: 8),
        Text(info['description']!, style: AppTheme.bodyStyle),
      ],
    );
  }

  Widget _buildFunctionCard({required IconData icon, required String title, required String subtitle, required VoidCallback onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: AppTheme.background,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: AppTheme.primaryColor.withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Icon(icon, size: 24, color: AppTheme.primaryColor),
            ),
            const SizedBox(height: 8),
            Text(title, style: AppTheme.bodyStyle.copyWith(fontWeight: FontWeight.bold)),
            Text(subtitle, style: AppTheme.bodyStyle.copyWith(fontSize: 12, color: AppTheme.textSecondary)),
          ],
        ),
      ),
    );
  }
}
